<template>
  <el-dialog
    v-model="visible"
    title="点赞管理"
    width="50%"
    :before-close="handleClose"
  >
    <div class="likes-section">
      <el-table
        :data="likeList"
        style="width: 100%"
        v-loading="likesLoading"
      >
        <el-table-column prop="like_id" label="点赞ID" width="80" />
        <el-table-column prop="user" label="点赞用户" min-width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar 
                :size="25" 
                :src="scope.row.user?.avatar"
              >
                {{ scope.row.user?.name?.charAt(0) }}
              </el-avatar>
              <span class="author-name">{{ scope.row.user?.name || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="点赞时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteLike(scope.row)"
            >
              取消点赞
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="likePagination.page"
          v-model:page-size="likePagination.limit"
          :page-sizes="[10, 20, 50]"
          :total="likePagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleLikeSizeChange"
          @current-change="handleLikeCurrentChange"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ShortVideo, ShortVideoLike as ShortVideoLikeType } from '@/api/modules/shortVideo'
import { 
  getShortVideoLikeList,
  unlikeShortVideo
} from '@/api/modules/shortVideo'

const props = defineProps<{
  modelValue: boolean
  videoData: ShortVideo | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = ref(false)

// 点赞列表
const likeList = ref<ShortVideoLikeType[]>([])
const likesLoading = ref(false)

// 点赞分页信息
const likePagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 获取点赞列表
const fetchLikes = async (videoId: number) => {
  likesLoading.value = true
  try {
    const response = await getShortVideoLikeList({
      video_id: videoId,
      page: likePagination.value.page,
      limit: likePagination.value.limit
    })
    
    likeList.value = response.data?.list || []
    if (response.data?.pagination) {
      likePagination.value.total = response.data.pagination.total || 0
    }
  } catch (error) {
    console.error('获取点赞列表失败:', error)
  } finally {
    likesLoading.value = false
  }
}

// 监听弹窗显示状态和视频数据变化
watch([() => props.modelValue, () => props.videoData], async ([newVisible, newVideoData]) => {
  visible.value = newVisible
  if (newVisible && newVideoData && newVideoData.video_id) {
    await fetchLikes(newVideoData.video_id)
  }
}, { immediate: true })

// 处理弹窗关闭
const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}

// 处理点赞分页大小变化
const handleLikeSizeChange = (val: number) => {
  likePagination.value.limit = val
  likePagination.value.page = 1
  if (props.videoData && props.videoData.video_id) {
    fetchLikes(props.videoData.video_id)
  }
}

// 处理点赞当前页变化
const handleLikeCurrentChange = (val: number) => {
  likePagination.value.page = val
  if (props.videoData && props.videoData.video_id) {
    fetchLikes(props.videoData.video_id)
  }
}

// 处理取消点赞
const handleDeleteLike = async (like: ShortVideoLikeType) => {
  ElMessageBox.confirm(
    `确定要取消该用户的点赞吗？此操作不可恢复！`,
    '确认取消点赞',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    } as any
  )
  .then(async () => {
    if (!like.video_id) return
    
    try {
      await unlikeShortVideo({ video_id: like.video_id })
      ElMessage.success('取消点赞成功')
      // 重新获取点赞列表
      if (props.videoData && props.videoData.video_id) {
        fetchLikes(props.videoData.video_id)
      }
    } catch (error) {
      console.error('取消点赞失败:', error)
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped>
.likes-section {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-name {
  margin-left: 5px;
  font-size: 12px;
}
</style>